package com.apes.fn.server.productRequireManage.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.scm.commodityInquiry.model.ExternalInquiryItem;
import com.apes.fn.scm.commodityInquiry.repository.ExternalInquiryItemRepository;
import com.apes.fn.server.productRequire.ProductRequire;
import com.apes.fn.server.productRequire.ProductRequireItem;
import com.apes.fn.server.productRequire.ProductRequireRepository;
import com.apes.fn.server.productRequire.ProductRequireService;
import com.apes.fn.server.productRequireManage.model.ReplenishmentBusinessImpAbstract;
import com.apes.fn.server.servicePlan.service.ServiceToForeign;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.soe.store.database.repository.SceneRepository;
import com.apes.framework.util.MapUtil;
import com.apes.scm.account.tax.repository.TaxRepository;
import com.apes.scm.contract.model.Contract;
import com.apes.scm.contract.repository.ContractRepository;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.pur.purchaseOrder.model.PurchaseOrder;
import com.apes.scm.pur.purchaseOrder.model.PurchaseOrderItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service(value = "externalInquiryRequirePurOrderService")
public class ExternalInquiryRequirePurOrderService extends ReplenishmentBusinessImpAbstract {

    @Autowired
    private ExternalInquiryItemRepository externalInquiryItemRepository;
    @Autowired
    private TaxRepository taxRepository;
    @Autowired
    private ProductRequireService productRequireService;

    public Map sendOrder(JSONObject obj) {
        ProductRequire productRequire = getBean(ProductRequireRepository.class).findOne(obj.getString("id"));

        // 获取单价
        List<String> inquiryIds = new ArrayList<>();
        for (ProductRequireItem requireItem: productRequire.getProductRequireItems()) {
            if (StringUtils.hasText(requireItem.getCommodityInquiryOrderId()) && requireItem.getCommodityInquiryOrderId().startsWith("WC")) inquiryIds.add(requireItem.getCommodityInquiryOrderId());
        }

        // 非外采或询价单号为空返回
        if (inquiryIds.isEmpty()) return MapUtil.mapper("isWC", false);

//        JSONArray inquiryArray =  getBean(ServiceToForeign.class).qryXJInfoFromOldSys(inquiryIds);

        PurchaseOrder purchaseOrder = new PurchaseOrder();
        purchaseOrder.setProductRequire(productRequire.getId()); // 设置要货单号，用于回写已到货数量
        purchaseOrder.setCompany(productRequire.getCompany());
        purchaseOrder.setLocation(productRequire.getLocation());
        purchaseOrder.setCreator(productRequire.getApproveId().getId());

        if (!Objects.isNull(productRequire.getCustomerExpand())) {
            purchaseOrder.setCustomerExpandId(productRequire.getCustomerExpand().getId());
            purchaseOrder.setCarLicense(productRequire.getCustomerExpand().getCarLicense());
        }
        purchaseOrder.setMoveType(SpringManager.getBean(EnumerationRepository.class).findOne("direct")); // 默认多次交货
        purchaseOrder.setOrigin(productRequire.getSource());
        purchaseOrder.setOriginBusinessType(productRequire.getSourceBusinessType());
        purchaseOrder.setOriginTypeName(productRequire.getSourceBusinessTypeName());

        Contract contract = SpringManager.getBean(ContractRepository.class).findAll(
                JpaDsl.toCriteria("cooperation.id", "EQ", "distribution",
                        "contractType.code", "IN", Arrays.asList("supplier", "platform"),
                        "partner.id", "EQ", "004465",
                        "company.id", "IN", Arrays.asList("1007", purchaseOrder.getCompany().getId()),
                        "state", "EQ", "approve",
                        "settlementType.code", "EQ", "deptCash"
                )
        ).stream().filter(c -> c.getValidPeriod().after(new Date())).findFirst().orElse(null);
        if (contract == null)throw new RuntimeException("采购合同异常，请检查公司(" + purchaseOrder.getCompany().getName() + ")下的现金采购经销合同，且结算方式为门店现金");

        purchaseOrder.setContract(contract);
        purchaseOrder.setClerk(contract.getPartner());
        purchaseOrder.setCooperation(contract.getCooperation());
        purchaseOrder.setSupplier(contract.getPartner());
        purchaseOrder.setDept(productRequire.getLocation().getDepot().getDept());
        purchaseOrder.setScene(SpringManager.getBean(SceneRepository.class).findOne("PO003"));


        List<ExternalInquiryItem> externalInquiryItems =  externalInquiryItemRepository.findAll(JpaDsl.toCriteria("externalInquiry.id", "in", inquiryIds));
        List<PurchaseOrderItem> purchaseOrderItems = productRequire.getProductRequireItems().stream().map(requireItem -> {
            PurchaseOrderItem purchaseOrderItem = new PurchaseOrderItem();

            // 获取外采备注
            ExternalInquiryItem externalInquiryItem = externalInquiryItems.stream().filter(inquiryItem -> {
                return inquiryItem.getExternalInquiry().getId().equals(requireItem.getCommodityInquiryOrderId()) && requireItem.getProduct().getId().equals(inquiryItem.getProduct().getId());
            }).findFirst().orElse(null);
            purchaseOrderItem.setNote(externalInquiryItem.getDeptRemark());
            purchaseOrderItem.setSettlementType(externalInquiryItem.getSettlementType());

            purchaseOrderItem.setProduct(requireItem.getProduct());
            purchaseOrderItem.setTax(taxRepository.findOne(Long.valueOf("5"))); // 无税

            String purchasePrice = externalInquiryItemRepository.sourceQueryPriceValid(requireItem.getCommodityInquiryOrderId(), requireItem.getUniqueValue()).get("PURCHASE_UNIT").toString();
            purchaseOrderItem.setPriceUnit(Double.valueOf(purchasePrice));
            purchaseOrderItem.setSourceItemId(requireItem.getId());

            purchaseOrderItem.setEffectiveQty(requireItem.getQtyRequire());
            purchaseOrderItem.setProductUomQty(requireItem.getQtyRequire());
            purchaseOrderItem.setUom(requireItem.getUom());
            purchaseOrderItem.setPurchaseOrder(purchaseOrder);
            purchaseOrderItem.computeAmt();
//            requireItem.setOrderQty(requireItem.getQtyRequire());
            return purchaseOrderItem;
        }).collect(Collectors.toList());
        purchaseOrder.setPurchaseItems(purchaseOrderItems);

        // 第一步，记录要货单的订货数量 -- 会产生死锁？？？
//        productRequire.setLastUpdatedStamp(new Date());
//        productRequireService.save(productRequire);

        // 第二步，生成采购单
        PurchaseOrder purchaseOrderNew = invoke("purchase.order.create", MapUtil.mapped(purchaseOrder));

        // 第三部，审核采购订单
        purchaseOrderNew.setApproveUid(productRequire.getApproveId());
        this.invoke("purchase.order.approve", MapUtil.mapped(purchaseOrderNew));

        // isWC 返回给调用类，如果是外采要货，调用类则不需要继续往下走
        return MapUtil.mapper("isWC", true);
    }


    // 获取采购单价
    private double getPurchaseUnit(JSONArray inquiryArray, ProductRequireItem productRequireItem){
        return inquiryArray.stream().filter( json -> {
            JSONObject item = (JSONObject) json;
            return productRequireItem.getCommodityInquiryOrderId().equals(item.getString("XJDH")) && productRequireItem.getProduct().getId().equals(item.getString("SPID"));
        }).collect(Collectors.toCollection(JSONArray::new)).getJSONObject(0).getDoubleValue("CGDJ");
    }
}
